package com.example.demo3.controller;

import java.util.Date;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtUtils {

	private long expire = 604800L;
	
	private String secret = "ji8n3439n439n43ld9ne9343fdfer49h";

	// 生成jwt
	public String generateToken(String username, String jwtId) {
		Date nowDate = new Date();
		Date expireDate = new Date(nowDate.getTime() + 1000 * expire);
		return Jwts.builder()
				.setId(jwtId)
				.setHeaderParam("typ", "JWT")
				.setSubject(username)
				.setIssuedAt(nowDate)
				.setExpiration(expireDate)// 7天過期
				.signWith(SignatureAlgorithm.HS512, secret)
				.compact();
	}

	// 解析jwt
	public Claims getClaimByToken(String jwt) {
		try {
			return Jwts.parser()
					.setSigningKey(secret)
					.parseClaimsJws(jwt)
					.getBody();
		} catch (Exception e) {
			return null;
		}
	}

	// jwt是否过期
	public boolean isTokenExpired(Claims claims) {
		return claims.getExpiration().before(new Date());
	}
	
	public static void main(String[] args) {
		String jwt="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJqdGkiOiIzZGRmZWNjNy1kNjRjLTRmMDMtYTkyMi1mNjIxNjc0MGVlY2MiLCJzdWIiOiJhZG1pbiIsImlhdCI6MTY3MjM4MDkwNSwiZXhwIjoxNjcyOTg1NzA1fQ._ysuGyBzIE5y2OlhoVjEMJlZx-cXzgRjBx0z0eHLFLKubM_lidby9hmrgFclGAlX8kdoco6ud_WynDqju71n7A";
		Claims c  =Jwts.parser()
				.setSigningKey("ji8n3439n439n43ld9ne9343fdfer49h")
				.parseClaimsJws(jwt)
				.getBody();
		System.out.println(c);
	}

}
